package org.jeecg.modules.demo.score.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.score.entity.ScoreInf;
import org.jeecg.modules.demo.score.service.IScoreInfService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 积分详情表
 * @Author: jeecg-boot
 * @Date:   2024-10-17
 * @Version: V1.0
 */
@Api(tags="积分详情表")
@RestController
@RequestMapping("/score/scoreInf")
@Slf4j
public class ScoreInfController extends JeecgController<ScoreInf, IScoreInfService> {
	@Autowired
	private IScoreInfService scoreInfService;
	@Autowired
	private ISysUserService sysUserService;
	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;
	 @Autowired
	 private ISysUserDepartService sysUserDepartService;
	 @Autowired
	 private ISysDictService sysDictService;
	
	/**
	 * 分页列表查询
	 *
	 * @param scoreInf
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "积分详情表-分页列表查询")
	@ApiOperation(value="积分详情表-分页列表查询", notes="积分详情表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ScoreInf>> queryPageList(ScoreInf scoreInf,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ScoreInf> queryWrapper = QueryGenerator.initQueryWrapper(scoreInf, req.getParameterMap());
		Page<ScoreInf> page = new Page<ScoreInf>(pageNo, pageSize);
		IPage<ScoreInf> pageList = scoreInfService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @ApiOperation(value="", notes="积分详情表-分页列表查询")
	 @GetMapping(value = "/queryPageListByUser")
	 public Result<IPage<ScoreInf>> queryPageListByUser(ScoreInf scoreInf,
												  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												  HttpServletRequest req) {
		 QueryWrapper<ScoreInf> queryWrapper = QueryGenerator.initQueryWrapper(scoreInf, req.getParameterMap());
		 //当前用户
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 String userId = sysUser.getId();

		 Map<String,Object> param = new HashMap<>();
		 param.put("orgCode",sysUser.getOrgCode());
		 //当前用户是否管理员
		 Integer isAdmin = scoreInfService.isAdmin(userId,"admin");
		 if(isAdmin>0){
			 param.put("managerUserId",userId);
		 }else{
			 param.put("ownerId",sysUser.getUsername());
		 }
		 param.put("scoreType",scoreInf.getScoreType());
		 param.put("isUsed",scoreInf.getIsUsed());
		 param.put("ownerDpetId",scoreInf.getOwnerDeptId());
		 param.put("ownerName",scoreInf.getOwnerName());
		 param.put("authStatus",scoreInf.getAuthStatus());
		 Page<ScoreInf> page = new Page<ScoreInf>(pageNo, pageSize);
		 IPage<ScoreInf> pageList = scoreInfService.getScoreInfListPage(page,param);
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param param
	 * @return
	 */
	@AutoLog(value = "积分详情表-添加")
	@ApiOperation(value="积分详情表-添加", notes="积分详情表-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:score_inf:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Map<String,List<ScoreInf>> param) {
		List<ScoreInf> scoreInfList = (List<ScoreInf>) param.get("scoreInfList");
		//当前用户
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();
		for(ScoreInf inf:scoreInfList){
			String ownerId = inf.getOwnerId();
			//自己申请的时候积分所属人为空
			if(oConvertUtils.isEmpty(ownerId)){
				inf.setOwnerId(sysUser.getUsername());
				inf.setOwnerName(sysUser.getRealname());
				DepartIdModel departIdModel = sysUserDepartService.queryDepartIdsOfUser(userId).get(0);
				inf.setOwnerDeptId(departIdModel.getValue());
				inf.setOwnerDeptName(departIdModel.getTitle());
				inf.setCreatedId(sysUser.getUsername());
				inf.setCreatedName(sysUser.getRealname());
			}else{
				//管理员直接添加
				//查询ownerId用户信息
				SysUser user = sysUserService.getUserByName(ownerId);
				String dept_id = sysUserDepartService.queryDepartIdsOfUser(user.getId()).get(0).getValue();
				inf.setOwnerName(user.getRealname());
				inf.setOwnerDeptId(dept_id);
				inf.setOwnerDeptName(user.getOrgCodeTxt());
				inf.setCreatedId(sysUser.getUsername());//申请人为当前用户
				inf.setCreatedName(sysUser.getRealname());
			}
		}
		scoreInfService.saveBatch(scoreInfList);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param param
	 * @return
	 */
	@AutoLog(value = "积分详情表-编辑")
	@ApiOperation(value="积分详情表-编辑", notes="积分详情表-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:score_inf:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody Map<String,List<ScoreInf>> param) {
		List<ScoreInf> scoreInfList = (List<ScoreInf>) param.get("scoreInfList");
		ScoreInf scoreInf = scoreInfList.get(0);
		scoreInfService.updateById(scoreInf);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "积分详情表-通过id删除")
	@ApiOperation(value="积分详情表-通过id删除", notes="积分详情表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:score_inf:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		scoreInfService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "积分详情表-批量删除")
	@ApiOperation(value="积分详情表-批量删除", notes="积分详情表-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:score_inf:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.scoreInfService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "积分详情表-通过id查询")
	@ApiOperation(value="积分详情表-通过id查询", notes="积分详情表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ScoreInf> queryById(@RequestParam(name="id",required=true) String id) {
		ScoreInf scoreInf = scoreInfService.getById(id);
		if(scoreInf==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(scoreInf);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param scoreInf
    */
    //@RequiresPermissions("org.jeecg.modules.demo:score_inf:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ScoreInf scoreInf) {
        return super.exportXls(request, scoreInf, ScoreInf.class, "积分详情表");
    }
    /**
    * 导出excel
    *
    * @param request
    * @param scoreInf
    */
    //@RequiresPermissions("org.jeecg.modules.demo:score_inf:exportXls")
    @RequestMapping(value = "/export")
    public ModelAndView export(HttpServletRequest request, ScoreInf scoreInf) {
		// Step.2 获取导出数据
		//当前用户
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userId = sysUser.getId();

		Map<String,Object> param = new HashMap<>();
		param.put("orgCode",sysUser.getOrgCode());
		//当前用户是否管理员
		Integer isAdmin = scoreInfService.isAdmin(userId,"admin");
		if(isAdmin>0){
			param.put("managerUserId",userId);
		}else{
			param.put("ownerId",userId);
		}
		param.put("scoreType",scoreInf.getScoreType());
		param.put("isUsed",scoreInf.getIsUsed());
		param.put("ownerDpetId",scoreInf.getOwnerDeptId());
		param.put("ownerName",scoreInf.getOwnerName());
		param.put("authStatus",scoreInf.getAuthStatus());
		List<ScoreInf> exportList = scoreInfService.getScoreInfList(param);
		String authstatusModels = sysDictService.queryDictTextByKey("auth_status","0");
		for(ScoreInf inf:exportList){
			inf.setAuthStatus(sysDictService.queryDictTextByKey("auth_status",inf.getAuthStatus()));
			inf.setScoreType(sysDictService.queryDictTextByKey("score_type",inf.getScoreType()));
			inf.setIsUsed(sysDictService.queryDictTextByKey("yn",inf.getIsUsed()));
		}
		String title = "积分详情表";
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, title);
		mv.addObject(NormalExcelConstants.CLASS, ScoreInf.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams  exportParams=new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		exportParams.setImageBasePath(upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS,exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("score_inf:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ScoreInf.class);
    }

}
